//
//  PictureSelectorViewController.swift
//  SinaBlog
//
//  Created by macs on 15/11/19.
//  Copyright © 2015年 BlackTail. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"
//列数
private let colume : CGFloat = 4.0
//间隙宽度
private let pictureCellMargin : CGFloat = 10.0
//最大视图添加个数
private let maxImageCount = 4

class PictureSelectorViewController: UICollectionViewController {
    
    
    lazy var iconArray = [UIImage]()
    
    init() {
        
        let layout = UICollectionViewFlowLayout()
        //计算 cell 大小
        let cellW = (screenW - (colume + 1) * pictureCellMargin) / colume
        layout.itemSize = CGSize(width: cellW, height: cellW)
        layout.minimumLineSpacing = pictureCellMargin
        layout.minimumInteritemSpacing = pictureCellMargin
        //设置行间距
        layout.sectionInset = UIEdgeInsets(top: pictureCellMargin, left: pictureCellMargin, bottom: 0, right: pictureCellMargin)
        super.init(collectionViewLayout: layout)
        collectionView?.backgroundColor = UIColor.randomColor()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.collectionView!.registerClass(PicSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        
    }
    
    // MARK: UICollectionViewDataSource
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        let delat = (iconArray.count == maxImageCount) ? 0 : 1
        return  iconArray.count + delat
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PicSelectorCell
        cell.pictureSelectorDelegate = self
        //        cell.backgroundColor = UIColor.randomColor()
        //判断
        if indexPath.item == iconArray.count {
            cell.icon = nil
        } else {
            cell.icon = iconArray[indexPath.item]
        }
        
        return cell
    }
    
}

extension PictureSelectorViewController : PicSelectorCellDelegate {
    
    func addPicture(cell : PicSelectorCell) {
        
        if cell.icon != nil {
            
            print("已经添加了图片") 
            return
        }
        
        //添加图片
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        
        //设置图片是否可以编辑,截图是开启
        //        imagePicker.allowsEditing = true
        
        presentViewController(imagePicker, animated: true, completion: nil)
    }
    
    func deletePicture(picseletor: PicSelectorCell) {
        //删除图片
        let indexpath = collectionView?.indexPathForCell(picseletor)
        iconArray.removeAtIndex((indexpath?.item)!)
        
        //刷新视图的动画
        UIView.animateWithDuration(0.5, animations: { () -> Void in
            picseletor.alpha = 0
            }) { (_) -> Void in
                picseletor.alpha = 1
                self.collectionView?.reloadData()
        }
        
        
    }
    
}

extension PictureSelectorViewController : UIImagePickerControllerDelegate ,UINavigationControllerDelegate{
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        //        print(image)
        //        print(editingInfo)
        iconArray.append(image)
        collectionView?.reloadData()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
}


@objc protocol PicSelectorCellDelegate {
    
    //添加,删除图片的协议方法
    optional func addPicture(cell : PicSelectorCell)
    
    optional func deletePicture(picseletor : PicSelectorCell)
    
}

class PicSelectorCell : UICollectionViewCell {
    
    @objc private func addBtnDidClick () {
        //这里用方法后面用?,当没有实现该方法时不会报错
        pictureSelectorDelegate?.addPicture?(self)
    }
    
    @objc private func deleBtnDidClick () {
        pictureSelectorDelegate?.deletePicture?(self)
    }
    
    
    var icon : UIImage? {
        
        didSet {
            deleBtn.hidden = (icon == nil)
            if icon != nil{
                addBtn.setBackgroundImage(icon, forState: .Normal)
            }
            else {
                //当删除图片后, image 为空执行下面的操作
                addBtn.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: .Normal)
            }
        }
    }
    
    //定义代理属性
    var pictureSelectorDelegate : PicSelectorCellDelegate?
    
    //3.重写构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //2.添加子控件,设置约束
    func setupUI () {
        
        contentView.addSubview(addBtn)
        contentView.addSubview(deleBtn)
        
        addBtn.addTarget(self, action: "addBtnDidClick", forControlEvents: .TouchUpInside)
        
        deleBtn.addTarget(self, action: "deleBtnDidClick", forControlEvents: .TouchUpInside)
        
        addBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
        
        deleBtn.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(contentView.snp_right)
            make.top.equalTo(contentView.snp_top)
        }
        
    }
    
    //1.懒加载控件
    lazy var addBtn = UIButton(title: nil, color: nil, icon: "compose_pic_add")
    lazy var deleBtn = UIButton(title: nil, color: nil, icon: "compose_photo_close")
    
}





